package jmine.tec.hydra.dao;

import java.util.List;

import jmine.tec.hydra.api.MessageDirection;
import jmine.tec.hydra.domain.HydraRequestImpl;
import jmine.tec.hydra.domain.HydraSystem;
import jmine.tec.hydra.domain.message.HydraMessageImpl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.hibernate.RestrictionsUtils;

/**
 * DAO de HydraMessageImpl
 * 
 * @author lundberg
 */
public class HydraMessageImplDAO extends BaseDAO<HydraMessageImpl> {

    /**
     * Busca todas as mensagens associadas à requisição.
     * 
     * @param request request
     * @return List de HydraMessageImpl
     */
    public List<HydraMessageImpl> findByRequest(HydraRequestImpl request) {
        Criteria crit = this.createCriteria();
        crit.add(Restrictions.eq("requestId", request.getId()));
        crit.addOrder(Order.asc("id"));
        return this.executeQuery(crit);
    }

    /**
     * Busca todas as mensagens associadas à requisição com a direção dada.
     * 
     * @param request request
     * @param direction direction
     * @return List de HydraMessageImpl
     */
    public List<HydraMessageImpl> findByRequestDirection(HydraRequestImpl request, MessageDirection direction) {
        Criteria criteria = this.createCriteria();
        RestrictionsUtils.addRestrictionEqId(criteria, "requestId", request);
        RestrictionsUtils.addRestrictionEq(criteria, "direction", direction);
        criteria.addOrder(Order.asc("id"));
        return this.executeQuery(criteria);
    }

    /**
     * Busca todas as mensagens que tiverem os parâmetros especificados.
     * 
     * @param direction direction
     * @param system system
     * @param action action
     * @return List de HydraMessageImpl
     */
    public List<HydraMessageImpl> findBy(MessageDirection direction, HydraSystem system, String action) {
        Criteria criteria = this.createCriteria();
        criteria.createAlias("conversation", "CONVERS");
        criteria.createAlias("CONVERS.specification", "SPEC");
        RestrictionsUtils.addRestrictionEq(criteria, "direction", direction);
        RestrictionsUtils.addRestrictionEq(criteria, "SPEC.system", system);
        RestrictionsUtils.addRestrictionEq(criteria, "SPEC.action", action);
        criteria.addOrder(Order.asc("id"));
        return this.executeQuery(criteria);
    }

}
